<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>{{ t('login.title') }}</h2>
        </div>
      </template>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :placeholder="t('login.usernamePlaceholder')"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            :placeholder="t('login.passwordPlaceholder')"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item prop="captcha_text">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha_text"
              :placeholder="t('login.captchaPlaceholder')"
              prefix-icon="Picture"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image-container">
              <img
                v-if="captchaImage"
                :src="captchaImage"
                alt="验证码"
                class="captcha-image"
                @click="refreshCaptcha"
                :title="t('login.clickToRefresh')"
              />
              <el-button
                v-else
                type="primary"
                :loading="captchaLoading"
                @click="refreshCaptcha"
              >
                {{ t('login.getCaptcha') }}
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <div @click="handleLogin" style="width: 100%;">
            <el-button
              type="primary"
              :loading="authStore.loading"
              class="login-button"
              style="width: 100%; pointer-events: none;"
            >
              {{ t('login.loginButton') }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <div v-if="authStore.error" class="error-message">
        <el-alert
          :title="authStore.error"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <div class="demo-info">
        <el-alert
          :title="t('login.demoAccount')"
          type="info"
          :closable="false"
        >
          <p>{{ t('login.demoUsername') }}</p>
          <p>{{ t('login.demoPassword') }}</p>
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const router = useRouter()
const authStore = useAuthStore()

const loginFormRef = ref<FormInstance>()
const loginForm = reactive({
  username: '',
  password: '',
  captcha_text: ''
})

const loginRules: FormRules = {
  username: [
    { required: true, message: t('login.usernameRequired'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('login.passwordRequired'), trigger: 'blur' },
    { min: 6, message: t('login.passwordMinLength'), trigger: 'blur' }
  ],
  captcha_text: [
    { required: true, message: t('login.captchaRequired'), trigger: 'blur' }
  ]
}

// 验证码相关
const captchaImage = ref('')
const captchaLoading = ref(false)
const captchaId = ref('')

// 生成验证码ID
const generateCaptchaId = () => {
  return `captcha_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 刷新验证码
const refreshCaptcha = async () => {
  captchaLoading.value = true
  try {
    captchaId.value = generateCaptchaId()
    const response = await fetch('/api/captcha/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        session_id: captchaId.value
      })
    })
    
    if (response.ok) {
      const data = await response.json()
      captchaImage.value = data.captcha_image
    } else {
      ElMessage.error(t('login.getCaptchaFailed'))
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error(t('login.getCaptchaFailed'))
  } finally {
    captchaLoading.value = false
  }
}

// 页面加载时获取验证码
onMounted(() => {
  console.log('LoginView mounted')
  console.log('authStore.loading on mount:', authStore.loading)
  authStore.initUser()
  if (authStore.isAuthenticated) {
    router.push('/dashboard')
  } else {
    refreshCaptcha()
  }
})

const handleLogin = async () => {
  console.log('handleLogin called')
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    console.log('Form validation result:', valid)
    if (valid) {
      // 构建登录数据，包含验证码信息
      const loginData = {
        ...loginForm,
        captcha_id: captchaId.value
      }
      
      const result = await authStore.login(loginData)
      
      if (result.success) {
        ElMessage.success(t('login.loginSuccess'))
        router.push('/dashboard')
      } else {
        // Error is already set in the authStore
        ElMessage.error(result.error || t('login.loginFailed'))
        // 登录失败后刷新验证码
        refreshCaptcha()
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-color-secondary);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(0, 122, 255, 0.03) 0%, transparent 70%);
  animation: float 20s infinite ease-in-out;
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
  }
  33% {
    transform: translate(30px, -30px) rotate(120deg);
  }
  66% {
    transform: translate(-20px, 20px) rotate(240deg);
  }
}

.login-card {
  width: 100%;
  max-width: 420px;
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-xl);
  overflow: hidden;
  position: relative;
  z-index: 1;
  animation: slideUp 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card-header {
  text-align: center;
  padding: 32px 32px 24px;
  background-color: var(--bg-color-tertiary);
  border-bottom: 1px solid var(--border-color-light);
}

.card-header h2 {
  margin: 0;
  color: var(--text-color);
  font-size: 28px;
  font-weight: 700;
  letter-spacing: -0.01em;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 17px;
  font-weight: 600;
  letter-spacing: -0.01em;
  margin-top: 8px;
}

.error-message {
  margin-top: 16px;
}

.demo-info {
  margin-top: 16px;
  padding: 16px;
  background-color: var(--bg-color-tertiary);
  border: 1px solid var(--border-color-light);
  border-radius: var(--radius-lg);
}

.demo-info p {
  margin: 4px 0;
  font-size: 14px;
  color: var(--text-color-secondary);
  font-weight: 500;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-image-container {
  flex-shrink: 0;
}

.captcha-image {
  width: 120px;
  height: 48px;
  cursor: pointer;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  object-fit: contain;
  transition: all 0.2s ease;
}

.captcha-image:hover {
  border-color: var(--button-bg);
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    max-width: 100%;
    border-radius: 0;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  .card-header {
    padding: 24px 24px 20px;
  }
  
  .card-header h2 {
    font-size: 24px;
  }
  
  .demo-info {
    margin: 0 16px 16px;
  }
}
</style>
